package com.skydonkey.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.processing.OperationStatus;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.UrlSafeBase64;
import com.skydonkey.properties.QiniuProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class QiniuUtils {

    private static final Logger log = LoggerFactory.getLogger(QiniuUtils.class);

    private final OperationManager operationManager;
    private final UploadManager uploadManager;

    QiniuProperties qiniuProperties;


    public QiniuUtils(@Autowired QiniuProperties qiniuProperties) {
        this.qiniuProperties = qiniuProperties;
        Configuration cfg = new Configuration();
        this.operationManager = new OperationManager(qiniuProperties.getAuth(), cfg);
        this.uploadManager  = new UploadManager(cfg);
    }

    public QiniuProperties getQiniuProperties() {
        return qiniuProperties;
    }

    public QiniuUtils setQiniuProperties(QiniuProperties qiniuProperties) {
        this.qiniuProperties = qiniuProperties;
        return this;
    }

    public String uploadFile(String filename, byte[] fileData) {
        return uploadFile(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey(), qiniuProperties.getBucket(), filename, fileData);
    }


    // 上传文件到七牛云并返回文件的下载URL
    public String uploadFile(String accessKey, String secretKey, String bucket, String filename, byte[] fileData) {
        String upToken = qiniuProperties.getAuth().uploadToken(bucket);
        Configuration cfg = new Configuration();

        try {
            String key = filename;
            Response response = uploadManager.put(fileData, key, upToken);
            DefaultPutRet putRet = new DefaultPutRet();
            putRet = ObjectMapperUtil.toObject(response.bodyString(), DefaultPutRet.class);
            log.info("上传成功，文件的hash: " + putRet.hash);
            log.info("上传成功，文件的key: " + putRet.key);
            String downloadUrl = "http://" + qiniuProperties.getBucketDomain() + "/" + key;
            log.info("上传成功, 文件的url: " + downloadUrl);
            //String downloadUrl = downloadFile("http://" + qiniuProperties.getBucketDomain() + "/", key, "path/to/save/downloaded/file.jpg");
            return downloadUrl;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // 下载文件并返回本地文件路径
    public String downloadFile(String bucketDomain, String key, String localFilePath) {
        try {
            URL url = new URL(bucketDomain + key);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            int responseCode = httpURLConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = httpURLConnection.getInputStream();
                File outputFile = new File(localFilePath);
                OutputStream outputStream = new FileOutputStream(outputFile);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                inputStream.close();
                outputStream.close();

                System.out.println("文件下载成功，已保存至：" + localFilePath);
                return localFilePath;
            } else {
                System.out.println("文件下载失败，HTTP响应码：" + responseCode);
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // 转换mp4为flv文件
    public String convertMp4ToFlv(String fileName) throws QiniuException {
        String fops = "avthumb/flv";
        String newName = fileName.substring(0, fileName.lastIndexOf(".")) + ".flv";
        String saveAs =  UrlSafeBase64.encodeToString(qiniuProperties.getBucket()+":" + newName);   // 结果保存的路径，例如 "bucket:target.flv"
        String persistId = operationManager.pfop(qiniuProperties.getBucket(), fileName, fops, null, saveAs, true);
        return persistId;
    }


    // 根据persistedId查询转换状态
    public OperationStatus queryStatus(String persistId) throws QiniuException {
        return operationManager.prefop(persistId);
    }

}
